import datetime
import os


class FileGeneratorDao:
    def __init__(self, base_dir="D:\\test", template=None):
        """
        初始化文件生成器

        :param base_dir: 文件保存的根目录
        :param template: 文件内容模板，支持 {key} 格式的占位符
        """
        self.base_dir = base_dir
        self.template = template or """
import datetime
import json
from io import BytesIO

from flask import request, jsonify, Response
from openpyxl.workbook import Workbook
from sqlalchemy import func, and_, union, desc, text
from sqlalchemy.exc import IntegrityError

from tzq.document_management_system import dms_bp
from tzq.document_management_system.model.log_model import Log, Version
from tzq.document_management_system.model.{model_key}_model import {class_name}
from tzq.document_management_system.model.permission_model import Permission
from tzq.extensions import db


# layui多条件分页查询接口
@dms_bp.route('/api/{api_name}', methods=['GET'])
def get_{key}():
    page = int(request.args.get('page', 1))
    limit = int(request.args.get('limit', 10))

    principal = request.values.get("principal")
    online_date = request.values.get("online_date")
    created_by = request.values.get("created_by")
    # 获取搜索参数 - 业务字段

    query = {class_name}.query
    query = query.filter({class_name}.delete_flag == 'N')
    if principal: query = query.filter({class_name}.principal.ilike(f'%{{principal}}%'))
    if online_date: query = query.filter({class_name}.online_date == f'{{online_date}}')
    if created_by: query = query.filter({class_name}.created_by.ilike(f'%{{created_by}}%'))
    # 应用搜索条件 - 业务字段

    sort_field = request.args.get('field', '{primary_key}')
    sort_order = request.args.get('order', 'desc')
    if hasattr({class_name}, sort_field):
        if sort_order == 'asc':
            order_by = getattr({class_name}, sort_field).asc()
        else:
            order_by = getattr({class_name}, sort_field).desc()
        query = query.order_by(order_by)
    else:
        query = query.order_by({class_name}.online_date.desc(), {class_name}.{primary_key}.desc())
    pagination = query.paginate(page=page, per_page=limit, error_out=False)
    return jsonify({{
        'code': 0,
        'msg': '',
        'count': pagination.total,
        'data': [dataInfo.to_dict() for dataInfo in pagination.items]
    }})


def check_ip_modify_permission(client_ip_i: str):
    # 检查客户端用户，是否有新增、修改、删除权限
    permission_temp = Permission.query.filter(
        and_(Permission.ip == client_ip_i, Permission.user_type.in_(['管理员', '读写用户']),
             Permission.delete_flag == 'N')).first()
    if not permission_temp:
        return False
    else:
        return True


def is_administrator(client_ip_i: str):
    # 检查用户IP是否为管理员
    permission_temp = Permission.query.filter(
        and_(Permission.ip == client_ip_i, Permission.user_type.in_(['管理员']),
             Permission.delete_flag == 'N')).first()
    if not permission_temp:
        return False
    else:
        return True


@dms_bp.route('/api/{api_name}Update', methods=['POST'])
def {key}_update_cell():
    # layui的table的单元格编辑，保存到后台
    try:
        # 判断是否有更新权限
        client_ip = request.remote_addr
        if not check_ip_modify_permission(client_ip):
            return jsonify({{'status': 'error', 'message': f'你({{client_ip}})没有更新权限，请联系管理员twx1014920！'}}), 200
        data = request.json
        instance_temp = {class_name}.query.get(data['id'])
        if not instance_temp:
            return jsonify({{'status': 'error', 'message': 'Data Info not found'}}), 404
        # 判断该条信息是否是创建人，同时用户不能为管理员。
        if instance_temp.created_by != client_ip and not is_administrator(client_ip):
            return jsonify({{'status': 'error', 'message': f'该记录不是你创建的，你无法修改！'}}), 200

        v_old_value = ''
        v_new_value = data['value']
        
        if data['field'] == 'principal':
            v_old_value = instance_temp.principal
            instance_temp.principal = data['value']
            instance_temp.last_update_date = func.now()
            instance_temp.last_updated_by = client_ip
        elif data['field'] == 'online_date':
            v_old_value = instance_temp.online_date.strftime('%Y-%m-%d')
            instance_temp.online_date = data['value']
            instance_temp.last_update_date = func.now()
            instance_temp.last_updated_by = client_ip
        elif data['field'] == 'comment':
            v_old_value = instance_temp.comment
            instance_temp.comment = data['value']
            instance_temp.last_update_date = func.now()
            instance_temp.last_updated_by = client_ip
        # 更新对应字段 - 业务字段
        
        log = Log(
            business_type='{business_type}',
            log_type='修改',
            ip=client_ip,
            field_name=data['field'],
            old_value=v_old_value,
            new_value=v_new_value,
        )
        db.session.add(log)
        db.session.commit()
        return jsonify({{'status': 'success'}})
    except Exception as e:
        db.session.rollback()
        return jsonify({{'status': 'error', 'message': str(e)}}), 500


@dms_bp.route('/api/add{class_name}', methods=['POST'])
def add_{key}():
    # 添加数据接口
    data = request.get_json()
    client_ip = request.remote_addr
    # 判断是否有权限
    if not check_ip_modify_permission(client_ip):
        return jsonify({{'status': 'error', 'message': f'你({{client_ip}})没有添加权限，请联系管理员twx1014920！'}}), 200

    try:
        instance_temp = {class_name}(
            # 业务字段
            
            principal=data['principal'],
            online_date=data['online_date_template'],
            comment=data['comment'],
            created_by=client_ip,
            last_updated_by=client_ip
        )
        db.session.add(instance_temp)
        db.session.commit()
        return jsonify({{"code": 0, "msg": "添加成功"}})
    except IntegrityError:
        return jsonify({{"code": 1, "msg": "数据已存在"}}), 400
    except Exception as e:
        return jsonify({{"code": 2, "msg": str(e)}}), 500


@dms_bp.route('/api/{api_name}/<int:id>', methods=['DELETE'])
def delete_{key}(id):
    # 软删除数据接口
    instance_temp = {class_name}.query.get_or_404(id)
    try:
        # 判断是否有权限
        client_ip = request.remote_addr
        if not check_ip_modify_permission(client_ip):
            return jsonify({{'status': 'error', 'message': f'你({{client_ip}})没有删除权限，请联系管理员twx1014920！'}}), 200
        # 判断该条信息是否是创建人；
        if instance_temp.created_by != client_ip and not is_administrator(client_ip):
            return jsonify({{'status': 'error', 'message': f'该记录不是你创建的，你无法删除！'}}), 200
        v_old_value = json.dumps(instance_temp.to_dict())
        instance_temp.delete_flag = 'Y'
        instance_temp.last_update_date = func.now()
        instance_temp.last_updated_by = client_ip
        log = Log(
            business_type='{business_type}',
            log_type='删除',
            ip=client_ip,
            old_value=v_old_value,
        )
        db.session.add(log)
        db.session.commit()
        return jsonify({{"code": 0, "msg": "删除成功"}})
    except Exception as e:
        return jsonify({{"code": 1, "msg": str(e)}}), 500


@dms_bp.route('/api/export{class_name}', methods=['GET', 'POST'])
def export_{key}():
    # 数据导出
    principal = request.values.get("principal")
    online_date = request.values.get("online_date")
    created_by = request.values.get("created_by")
    # 获取搜索参数 - 业务字段

    query = {class_name}.query
    query = query.filter({class_name}.delete_flag == 'N')
    if principal: query = query.filter({class_name}.principal.ilike(f'%{{principal}}%'))
    if online_date: query = query.filter({class_name}.online_date == f'{{online_date}}')
    if created_by: query = query.filter({class_name}.created_by.ilike(f'%{{created_by}}%'))
    # 应用搜索条件 - 业务字段

    query = query.order_by({class_name}.online_date.desc(), {class_name}.last_update_date.desc())
    query = query.paginate(page=1, per_page=1000000, error_out=False)

    wb = Workbook()
    ws = wb.active
    ws.title = "{excel_title}"

    # 写入表头
    ws.append([
        # 表头 - 业务字段
        
        'Last Update Date', '责任人', '上线日期'
    ])
    # 写入数据
    for item in query:
        ws.append([
                   # 数据 - 业务字段
                   
                   '',  # 最后更新时间可以不写，导入的时候就是当前时间了
                   item.principal,
                   item.online_date.strftime('%Y-%m-%d')
                   ])

    date_string = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")

    # 将工作簿写入 BytesIO 流
    output = BytesIO()
    wb.save(output)
    output.seek(0)

    # 使用 Response 返回 Excel 文件
    return Response(
        output.getvalue(),
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        headers={{
            "Content-Disposition": "attachment; filename=" + date_string + "-jalor-{key}.xlsx"  # 文件名不能为中文，不然报错了
        }}
    )


@dms_bp.route('/api/get{class_name}OnlineDate', methods=['GET'])
def get_{key}_online_date():
    # 前端页面下拉框展示使用
    try:
        # 查询 delete_flag = 'N' 的 去重后 根据 online_date 倒叙排序的所有 online_date 的值
        data_list = db.session.query({class_name}.online_date.label('online_date')).filter(
            {class_name}.delete_flag == 'N').distinct()
        subquery_b = db.session.query(Version.online_date.label('online_date')).distinct()
        union_query = union(data_list, subquery_b)
        result = db.session.execute(union_query.order_by(desc(text('online_date')))).fetchall()
        
        # 提取结果（因为返回的是元组列表）, 提取元组中的第一个元素
        online_date_data = [{{"online_date": item[0].strftime('%Y-%m-%d')}} for item in result]
        return jsonify({{"code": 0, "msg": "", "count": len(online_date_data), "data": online_date_data}})
    except Exception as e:
        print("Database error:", e)
        return jsonify({{"code": -1, "msg": str(e), "count": 0, "data": None}})

"""
        # 确保目录存在
        if not os.path.exists(self.base_dir):
            os.makedirs(self.base_dir)

    def generate_files(self, data_list):
        """
        批量生成文件

        :param data_list: 字典列表，每个字典包含 file_name 和其他用于模板的字段
        """
        file_name = ""
        for data in data_list:
            if 'file_name' not in data:
                print("警告：缺少 file_name 字段，跳过该条目")
                continue
            date_string = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
            # 创建多层文件夹（自动处理父目录，并忽略已存在错误）
            os.makedirs(os.path.join(self.base_dir, date_string), exist_ok=True)
            # data['file_name'] = date_string + "-" + data['file_name']
            file_path = os.path.join(self.base_dir, date_string, data['file_name'])

            try:
                # 使用字典展开填充模板
                content = self.template.format(**data)
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                print(f"✅ 已生成文件: {file_path}")
            except KeyError as e:
                print(f"❌ 模板中使用的变量 {e} 在数据中不存在，文件 {data['file_name']} 生成失败。")
            except Exception as e:
                print(f"❌ 写入文件失败 {file_path}: {e}")


# 示例使用
if __name__ == "__main__":
    # 模拟数据
    data_list = [
        {"序号": "1", "model_key": "lookup", "key": "lookup_classify", "dao_name": "lookup_classify_dao",
         "file_name": "lookup_classify_dao.py", "class_name": "LookupClassify", "api_name": "lookupClassify",
         "primary_key": "lookup_classify_id", "business_type": "Lookup Classify", "excel_title": "Lookup Classify"}
        , {"序号": "2", "model_key": "lookup", "key": "lookup_item", "dao_name": "lookup_item_dao",
           "file_name": "lookup_item_dao.py", "class_name": "LookupItem", "api_name": "lookupItem",
           "primary_key": "lookup_item_id", "business_type": "Lookup Item", "excel_title": "Lookup Item"}
        , {"序号": "3", "model_key": "lookup", "key": "lookup_delete", "dao_name": "lookup_delete_dao",
           "file_name": "lookup_delete_dao.py", "class_name": "LookupDelete", "api_name": "lookupDelete",
           "primary_key": "lookup_delete_id", "business_type": "Lookup手工删除", "excel_title": "Lookup Delete"}
        , {"序号": "4", "model_key": "lookup", "key": "lookup_disable", "dao_name": "lookup_disable_dao",
           "file_name": "lookup_disable_dao.py", "class_name": "LookupDisable", "api_name": "lookupDisable",
           "primary_key": "lookup_disable_id", "business_type": "Lookup手工失效", "excel_title": "Lookup Disable"}
        , {"序号": "5", "model_key": "catalog", "key": "catalog", "dao_name": "catalog_dao",
           "file_name": "catalog_dao.py", "class_name": "Catalog", "api_name": "catalog", "primary_key": "catalog_id",
           "business_type": "菜单", "excel_title": "SiteNode"}
        , {"序号": "6", "model_key": "catalog", "key": "catalog_modify", "dao_name": "catalog_modify_dao",
           "file_name": "catalog_modify_dao.py", "class_name": "CatalogModify", "api_name": "catalogModify",
           "primary_key": "catalog_modify_id", "business_type": "菜单修改", "excel_title": "Catalog Modify"}
        , {"序号": "7", "model_key": "catalog", "key": "catalog_delete", "dao_name": "catalog_delete_dao",
           "file_name": "catalog_delete_dao.py", "class_name": "CatalogDelete", "api_name": "catalogDelete",
           "primary_key": "catalog_delete_id", "business_type": "菜单删除", "excel_title": "Catalog Delete"}
        , {"序号": "8", "model_key": "function", "key": "function", "dao_name": "function_dao",
           "file_name": "function_dao.py", "class_name": "Function", "api_name": "function",
           "primary_key": "function_id", "business_type": "权限集", "excel_title": "Function Bas Information"}
        , {"序号": "9", "model_key": "function", "key": "function_permission", "dao_name": "function_permission_dao",
           "file_name": "function_permission_dao.py", "class_name": "FunctionPermission",
           "api_name": "functionPermission", "primary_key": "function_permission_id", "business_type": "权限集权限点",
           "excel_title": "Function Permission"}
        , {"序号": "10", "model_key": "function", "key": "function_catalog", "dao_name": "function_catalog_dao",
           "file_name": "function_catalog_dao.py", "class_name": "FunctionCatalog", "api_name": "functionCatalog",
           "primary_key": "function_catalog_id", "business_type": "权限集菜单", "excel_title": "Function Catalog"}
        , {"序号": "11", "model_key": "function", "key": "function_dimension", "dao_name": "function_dimension_dao",
           "file_name": "function_dimension_dao.py", "class_name": "FunctionDimension", "api_name": "functionDimension",
           "primary_key": "function_dimension_id", "business_type": "权限集维度", "excel_title": "Function Dimension"}
        , {"序号": "12", "model_key": "role", "key": "role", "dao_name": "role_dao", "file_name": "role_dao.py",
           "class_name": "Role", "api_name": "role", "primary_key": "role_id", "business_type": "角色",
           "excel_title": "Role"}
        , {"序号": "13", "model_key": "role", "key": "role_function", "dao_name": "role_function_dao",
           "file_name": "role_function_dao.py", "class_name": "RoleFunction", "api_name": "roleFunction",
           "primary_key": "role_function_id", "business_type": "角色权限集", "excel_title": "Roles Function"}
        , {"序号": "14", "model_key": "role", "key": "role_function_delete", "dao_name": "role_function_delete_dao",
           "file_name": "role_function_delete_dao.py", "class_name": "RoleFunctionDelete",
           "api_name": "roleFunctionDelete", "primary_key": "role_function_delete_id",
           "business_type": "取消角色权限集", "excel_title": "Roles Function Cancel"}
        , {"序号": "15", "model_key": "property", "key": "property", "dao_name": "property_dao",
           "file_name": "property_dao.py", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-计划", "excel_title": "Property-plan"}
        , {"序号": "16", "model_key": "property", "key": "property", "dao_name": "property_dao",
           "file_name": "property_dao.py", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-指令", "excel_title": "Property-ins"}
        , {"序号": "17", "model_key": "property", "key": "property", "dao_name": "property_dao",
           "file_name": "property_dao.py", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-公共", "excel_title": "Property-common"}
        , {"序号": "18", "model_key": "property", "key": "property", "dao_name": "property_dao",
           "file_name": "property_dao.py", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-监控", "excel_title": "Property-monitor"}
        , {"序号": "19", "model_key": "property", "key": "property", "dao_name": "property_dao",
           "file_name": "property_dao.py", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-eod", "excel_title": "Property-eod"}
        , {"序号": "20", "model_key": "property", "key": "property", "dao_name": "property_dao",
           "file_name": "property_dao.py", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-接入层", "excel_title": "Property-data cashplan"}
        , {"序号": "21", "model_key": "property", "key": "property", "dao_name": "property_dao",
           "file_name": "property_dao.py", "class_name": "Property", "api_name": "property",
           "primary_key": "property_id", "business_type": "字典-mon his", "excel_title": "Property-monitor his"}

    ]

    # 创建生成器并执行
    generator = FileGeneratorDao()
    generator.generate_files(data_list)
